import 'package:dear_lottery/tools/DL_drawNumbersView.dart';
import 'package:flutter/material.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:intl/intl.dart';

import '../tools/DL_Config.dart';
import '../tools/FL_Switch.dart';
import '../tools/models/DL_DataViewModel.dart';
import '../tools/models/DL_LottoModel.dart';

class DL_CheckerDetailVC extends StatefulWidget {
  DL_CheckerDetailVC({super.key, required this.myTicketNumbers});
  List myTicketNumbers;
  @override
  State<DL_CheckerDetailVC> createState() => _DL_CheckerDetailVCState();
}

class _DL_CheckerDetailVCState extends State<DL_CheckerDetailVC> {
  var _ticketNumbers = [];
  var _numbersMap = {};

  bool _isShowWin = false; //是否显示中间的结果
  late var _winningNumbers = []; //显示的中奖号码
  late var _allNumbers = []; //显示所有的号码
  late var _lottoModels = []; //所有数据

  void showWinningNumbers() {
    if (_isShowWin) {
      _lottoModels = _winningNumbers;
    } else {
      _lottoModels = _allNumbers;
    }

    setState(() {});
  }

  void _configData() {
    List allModels = DL_DataViewModel().DL_resultsModels;

    ///
    List<String> numbersList = [];
    for (Map element in _ticketNumbers) {
      var tNum = element['number'];
      numbersList.add(tNum);
    }

    for (DL_LottoModel lModel in allModels) {
      var name = lModel.lottery_name!;
      DateTime drawDateTimeUTC = DateTime.parse(lModel.draw_date!);
      var dateTimeString = DateFormat('dd/MMM/yyyy').format(drawDateTimeUTC);

      List balls = [];

      ///配对每个号码的中奖情况
      List allPrizes = lModel.all_prize_num!;
      for (var i = 0; i < allPrizes.length; i++) {
        Map prizeMap = allPrizes[i];
        List prizeNumbers = prizeMap['numbers'];
        for (String prizeNumber in prizeNumbers) {
          List<String> tNumberList = prizeNumber.split('');

          //避免号码过长
          if (tNumberList.length > numbersList.length) continue;

          ///
          bool winning = compearMatchingElements(numbersList, tNumberList);
          //取每期第一中奖
          if (i == 0) {
            List nums = [];
            for (var j = tNumberList.length - 1; j >= 0; j--) {
              String tNum = tNumberList[j];
              bool isRight = false;

              if (winning) {
                int numbersLength = numbersList.length;
                int mostSimilarLength = tNumberList.length;
                int idx = j - (mostSimilarLength - numbersLength);
                if (idx >= 0) {
                  String rNum = numbersList[idx];
                  if (tNum == rNum) {
                    isRight = true;
                  }
                }
              }

              var num = {'number': tNum, 'isRight': isRight, 'isNormal': false};
              nums.add(num);
            }

            ///
            var prizeAmount = lModel.first_prize.toString();
            var prize = prizeMap['title'];
            var title = 'Matched $prize';
            if (i == 0) {
              title = '$prize';
            }
            var numbersMap = {'title': title, 'balls': nums.reversed.toList()};

            ///cell数据模型
            var cellDataMap = {
              'title': name,
              'dateTime': dateTimeString,
              'numbersMap': numbersMap,
              'amount': prizeAmount + ' INR',
              'winning': winning
            };
            _allNumbers.add(cellDataMap);
            if (winning) {
              _winningNumbers.add(cellDataMap);
            }
          } else {
            if (winning && i != 0) {
              List nums = [];
              for (var j = tNumberList.length - 1; j >= 0; j--) {
                String tNum = tNumberList[j];
                bool isRight = false;

                int numbersLength = numbersList.length;
                int mostSimilarLength = tNumberList.length;
                int idx = j - (mostSimilarLength - numbersLength);
                if (idx >= mostSimilarLength) {
                  String rNum = numbersList[idx];
                  if (tNum == rNum) {
                    isRight = true;
                  }
                }
                var num = {
                  'number': tNum,
                  'isRight': isRight,
                  'isNormal': false
                };
                nums.add(num);
              }

              ///
              var prizeAmount = prizeMap['prizeAmount'];
              var prize = prizeMap['title'];
              var title = 'Matched $prize';
              if (i == 0) {
                title = '$prize';
              }
              var numbersMap = {
                'title': title,
                'balls': nums.reversed.toList()
              };

              ///cell数据模型
              var cellDataMap = {
                'title': name,
                'dateTime': dateTimeString,
                'numbersMap': numbersMap,
                'amount': prizeAmount + ' INR',
                'winning': winning
              };

              _winningNumbers.add(cellDataMap);
              _allNumbers.add(cellDataMap);
            }
          }
        }
      }
    }

    setState(() {
      _lottoModels = _allNumbers;
    });
  }

  bool compearMatchingElements(
      List<String> currentArray, List<String> subArray) {
    bool count = false;
    if (subArray.length > currentArray.length) {
      return count;
    }

    ///
    String cArr = currentArray.join('');
    String sArr = subArray.join('');
    if (right(cArr, sArr.length) == sArr) {
      count = true;
    }

    return count;
  }

  String right(String str, int length) {
    return str.substring(str.length - length);
  }

  @override
  void initState() {
    super.initState();

    for (var element in widget.myTicketNumbers) {
      _ticketNumbers.add(element);
    }
    _numbersMap = {'title': '', 'balls': _ticketNumbers};
    debugPrint('$_ticketNumbers');

    _configData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Checker Detail'),
        backgroundColor: DL_Config.DL_MainColor,
        foregroundColor: Colors.white,
        centerTitle: true,
      ),
      body: Container(
        color: DL_Config.DL_pageBgColor,
        child: Column(
          children: [
            headerView(),
            contentListView(),
          ],
        ),
      ),
    );
  }

  Widget contentListView() {
    return Expanded(
      child: ListView.builder(
          padding: const EdgeInsets.all(15),
          itemCount: _lottoModels.length,
          // itemCount: 2,
          itemBuilder: (BuildContext context, int index) {
            var model = _lottoModels[index];

            return listCell(model);
          }),
    );
  }

  Widget listCell(Map model) {
    var title = model['title'];
    var dateTime = model['dateTime'];
    bool winning = model['winning'];
    var amount = winning ? model['amount'] : '';
    var numbersMap = model['numbersMap'];

    return Container(
      padding: const EdgeInsets.only(top: 7.5, bottom: 7.5),
      // height: 140,
      child: GestureDetector(
        onTap: () {
          debugPrint('result');
          // _goToDetailPage(nums.reversed.toList());
        },
        child: Container(
          // margin: const EdgeInsets.fromLTRB(10, 7.5, 10, 7.5),
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10)),
          ),
          child: Column(children: [
            Container(
              margin: const EdgeInsets.only(left: 10, right: 10),
              // height: 40,
              // color: Colors.yellow,
              child: Row(children: [
                Container(
                  margin: const EdgeInsets.only(left: 5, top: 5),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(title,
                          style: TextStyle(
                            fontWeight: FontWeight.w700,
                            fontSize: 14,
                            color: HexColor('#d32f7d'),
                          )),
                      Text(dateTime,
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            fontSize: 11,
                            color: HexColor('#999999'),
                          )),
                    ],
                  ),
                ),
                const Spacer(),
                Text(
                  amount,
                  style: TextStyle(
                      fontWeight: FontWeight.w700,
                      fontSize: 15,
                      color: HexColor('#D32F7D')),
                ),
              ]),
            ),
            SizedBox(
              width: double.infinity,
              child: Row(
                children: [
                  Expanded(
                      child: Container(
                    // color: Colors.red,
                    alignment: Alignment.centerLeft,
                    child: drawingNumbersView(numbersMap),
                  )),
                ],
              ),
            )
          ]),
        ),
      ),
    );
  }

  Widget headerView() {
    return Container(
      // height: 110,
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.2), // 阴影颜色
            spreadRadius: 1, // 扩散半径
            blurRadius: 10, // 模糊半径
            offset: const Offset(0, 1), // 阴影偏移
          ),
        ],
      ),
      child: Column(
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const SizedBox(width: 20),
                const Text(
                  'My Ticket',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.black,
                  ),
                ),
                const Spacer(),
                const Text(
                  'Show Winning Only',
                  style: TextStyle(
                    fontWeight: FontWeight.w400,
                    fontSize: 11,
                    color: Colors.black,
                  ),
                ),
                FLSwitch(
                  isOpen: _isShowWin,
                  onPressed: (show) {
                    debugPrint('-----$show');
                    _isShowWin = show;
                    showWinningNumbers();
                  },
                ),
                const SizedBox(width: 15),
              ],
            ),
          ),
          drawingNumbersView(_numbersMap),
        ],
      ),
    );
  }

  Widget drawingNumbersView(var data) {
    return Container(
      margin: const EdgeInsets.all(15),
      child: DL_drawNumbersView(data: data),
    );
  }
}
